package com.cqeec.bootdemo.controller;


import com.cqeec.bootdemo.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    //定义一个地址用于本地地址存放图片文件
    @Value("${reg.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //获取用户上传的文件名
        String ogfile = file.getOriginalFilename();
        //随机生成文件名
        String filename = UUID.randomUUID().toString();
        //处理用户上传的文件名，获取文件后缀
        String suffix = ogfile.substring(ogfile.lastIndexOf("."));
        filename = filename + suffix;
        File dir = new File(path);
        //判断文件夹是否存在，不存在则创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //将文件保存到指定路径
        try {
            file.transferTo(new File(path + filename));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回文件路径
        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //文件输入流
            FileInputStream fileInputStream = new FileInputStream(new File(path + name));
            ServletOutputStream outputStream = response.getOutputStream();
            //设置文件类型
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭输入输出流
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
